package com.beyondprototype.batch.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;

import com.beyondprototype.batch.model.CustomerMarker;
import com.mongodb.bulk.BulkWriteResult;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CustomerMarkerService {

    @Autowired
    private MongoTemplate mongoTemplate;
    
    
    public int cleanUp() {
    	
    	log.info("Clean CustomerMarker");
    	
    	BulkWriteResult result = mongoTemplate.bulkOps(BulkMode.UNORDERED, CustomerMarker.class).remove(new Query()).execute();
    	
    	log.info("Deleted Count: " + result.getDeletedCount());
    	
    	return result.getDeletedCount();
    }
    
    public int create(List<? extends CustomerMarker> markers) {
    	
    	log.info("Record Count: " + markers.size());
    	
    	BulkWriteResult result = mongoTemplate.bulkOps(BulkMode.UNORDERED, CustomerMarker.class).insert(markers).execute();
   	 
    	log.info("Inserted Count: " + result.getInsertedCount());
    	
   	 	return result.getInsertedCount();
   }
    
   public int update(List<? extends CustomerMarker> markers) {
     	
    	log.info("Record Count: " + markers.size());
    	
    	List<Pair<Query,Update>> updateList = new ArrayList<>(markers.size());
    	
    	markers.forEach( marker -> {
    		Query query = new Query(new Criteria("localIdentifer").is(marker.getLocalIdentifer()));
    		
    		Update update = new Update();
    		update.set("markers", marker.getMarkers());
    		update.set("status", "Updated");
    		
    		updateList.add(Pair.of(query, update));
    	});
    	

    	BulkOperations bulkOps = mongoTemplate.bulkOps(BulkMode.UNORDERED, CustomerMarker.class);
    	
    	BulkWriteResult result = bulkOps.upsert(updateList).execute();
   	 
    	log.info("Modified Count: " + result.getModifiedCount());
    	
    	
   	 	return result.getModifiedCount();
   }
}
